import React, { createContext, useContext, useState, ReactNode } from 'react';
import { useAuth } from '../auth/AuthContext';
import { Post, /*Comment*/ } from './types';

interface CommunityContextType {
  posts: Post[];
  loading: boolean;
  createPost: (title: string, content: string) => Promise<void>;
  addComment: (postId: number, content: string) => Promise<void>;
  likePost: (postId: number) => Promise<void>;
  getPosts: () => Promise<void>;
}

const CommunityContext = createContext<CommunityContextType | null>(null);

export const useCommunity = () => {
  const context = useContext(CommunityContext);
  if (!context) {
    throw new Error('useCommunity must be used within a CommunityProvider');
  }
  return context;
};

interface CommunityProviderProps {
  children: ReactNode;
}

export const CommunityProvider: React.FC<CommunityProviderProps> = ({ children }) => {
  const [posts, setPosts] = useState<Post[]>([]);
  const [loading, setLoading] = useState(false);
  const { user } = useAuth();

  const createPost = async (title: string, content: string) => {
    if (!user) return;

    try {
      setLoading(true);
      const response = await fetch('/api/community/posts', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: user.id,
          username: user.username,
          title,
          content,
        }),
      });

      if (!response.ok) {
        throw new Error('创建帖子失败');
      }

      const newPost = await response.json();
      setPosts(prev => [newPost, ...prev]);
    } catch (error) {
      console.error('创建帖子错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const addComment = async (postId: number, content: string) => {
    if (!user) return;

    try {
      setLoading(true);
      const response = await fetch(`/api/community/posts/${postId}/comments`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          userId: user.id,
          username: user.username,
          content,
        }),
      });

      if (!response.ok) {
        throw new Error('添加评论失败');
      }

      const newComment = await response.json();
      setPosts(prev =>
        prev.map(post =>
          post.postId === postId
            ? { ...post, comments: [...post.comments, newComment] }
            : post
        )
      );
    } catch (error) {
      console.error('添加评论错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const likePost = async (postId: number) => {
    if (!user) return;

    try {
      setLoading(true);
      const response = await fetch(`/api/community/posts/${postId}/like`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ userId: user.id }),
      });

      if (!response.ok) {
        throw new Error('点赞失败');
      }

      setPosts(prev =>
        prev.map(post =>
          post.postId === postId
            ? { ...post, likes: post.likes + 1 }
            : post
        )
      );
    } catch (error) {
      console.error('点赞错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  const getPosts = async () => {
    try {
      setLoading(true);
      const response = await fetch('/api/community/posts');

      if (!response.ok) {
        throw new Error('获取帖子失败');
      }

      const postsData = await response.json();
      setPosts(postsData);
    } catch (error) {
      console.error('获取帖子错误:', error);
      throw error;
    } finally {
      setLoading(false);
    }
  };

  return (
    <CommunityContext.Provider value={{
      posts,
      loading,
      createPost,
      addComment,
      likePost,
      getPosts,
    }}>
      {children}
    </CommunityContext.Provider>
  );
};